<template>
    <view class="px-2 py-4">
        <form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
            :startUserSelectTasks="visibleUserSelectTasks" :startUserSelectAssignees="visibleUserSelectAssignees"
            :startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
            :resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />

    </view>
</template>

<script setup lang="ts">
import {
    onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed, watch } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as UserApi from '@/api/system/user/index'
import { SupervisionVO, SupervisionApi } from '@/api/oa/supervision'
import { useMessage, useToast } from 'wot-design-uni'


const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const resubmit = ref(0)
const fileList = ref([]) // 文件列表
const userList = ref<any[]>([])
const data = ref({ path: '' })
const headerObj = ref(
    {
        Authorization: 'Bearer ' + getAccessToken()
    }
)

// 指定审批人
const processDefineKey = ref<string>('oa_sealbase')
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const sealList = ref<any[]>([])
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
    attachment: []
})
/** 处理级别类型变更 */
const handleDeptTypeChange = async ({ value }: { value: number }) => {
    // 根据类型切换流程定义key
    startUserSelectTasks.value = []
    startUserSelectAssignees.value = {}
    if (value === undefined || value === null) return
    try {
        // 根据不同类型获取不同的流程定义Key
        processDefineKey.value = value === 0 ? 'oa_sealbase' : 'oa_sealenterprise'
        const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
            undefined,
            processDefineKey.value
        )
        if (!processDefinitionDetail) {
            toast.error('流程模型未配置，请检查！')
            return
        }
        startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
        console.log('startUserSelectTasks.value', startUserSelectTasks.value);
        // 设置指定审批人
        if (startUserSelectTasks.value?.length > 0) {
            // 设置校验规则
            for (const userTask of startUserSelectTasks.value) {
                startUserSelectAssignees.value[userTask.id] = []
                startUserSelectAssigneesFormRules.value[userTask.id] = [
                    {
                        required: true,
                        message: '请选择审批人',
                        validator: (value: any) => {
                            if (value && Array.isArray(value) && value.length > 0) {
                                return Promise.resolve();
                            } else {
                                return Promise.reject('审批人不能为空');
                            }
                        },
                        trigger: ['change']

                    }
                ]
            }
        }
    } catch (error) {
        console.error('获取流程定义失败', error)
        toast.error('获取流程定义失败，请重试')
    }
}
// 计算属性：过滤需要显示的审批人任务
const visibleUserSelectTasks = computed(() => {
    if (!startUserSelectTasks.value || startUserSelectTasks.value.length === 0) {
        return []
    }
    if (formData.value.deptType === 0 && formData.value.directorConsulted === '1') {
        return startUserSelectTasks.value.filter((task: any) =>
            task.name !== '分管领导'
        )
        // const Selectted = startUserSelectTasks.value.find(item => item.name == '分管领导')
        // Selectted

    }
    return startUserSelectTasks.value
})
const visibleUserSelectAssignees = computed(() => {
    if (!startUserSelectTasks.value || startUserSelectTasks.value.length === 0) {
        return []
    }
    if (formData.value.deptType === 0 && formData.value.directorConsulted === '1') {
        const Selectted = startUserSelectTasks.value.find((item: any) => item.name == '分管领导')
        if (Selectted && Selectted.id) {
            startUserSelectAssignees.value[Selectted.id] = [1]
        }
    }
    return startUserSelectAssignees.value
})

//表单项字段配置
const formFields = ref<any[]>([

    {
        type: 'input',
        prop: 'supName',
        label: '督办名称',
        placeholder: '请输入督办名称'
    },

    {
        type: 'select',
        prop: 'userId',
        label: '执行人',
        placeholder: '请选择执行人',
        options: () => userList.value, // 动态数据，确保 sealList 格式为 [{ id, sealName }]
        labelKey: 'nickname',
        valueKey: 'id',
        filterable: true,

    },
    {
        type: 'textarea',
        prop: 'content',
        label: '督办内容',
        placeholder: '请输入督办内容'
    },
    {
        type: 'datetime',
        prop: 'beginTime',
        label: '开始日期',
        placeholder: '请选择开始日期',
        datetimeType: 'datetime',
    },
    {
        type: 'datetime',
        prop: 'endTime',
        label: '预计结束日期',
        placeholder: '请选择预计结束日期',
        datetimeType: 'datetime',
    },
    {
        type: 'datetime',
        prop: 'realEndTime',
        label: '完成时间',
        placeholder: '请选择完成时间',
        datetimeType: 'datetime',
        visible: () => detailId.value !== null && detailId.value !== undefined
    },
    {
        type: 'select',
        prop: 'status',
        label: '督办状态',
        placeholder: '请选择督办状态',
        options: [

            {
                label: '进行中',
                value: 0
            },
            {
                label: '已完成',
                value: 1
            }
        ],
        labelKey: 'label',
        valueKey: 'value',
        filterable: true,
        visible: () => detailId.value !== null && detailId.value !== undefined

    },

    {
        type: 'upload', prop: 'url', label: '附件', placeholder: '请输入附件',
        action: globalConfig.uploadUrl,
        limit: 1,
        accept: 'all',
        header: headerObj.value,
        targetMapping: {         // 字段映射配置
            fileUrl: 'url',    // 接口返回ID -> formData.serverIds
            fileName: 'ename'     // 文件名 -> formData.fileName
        }
    },

])//表单项字段配置
const formData = ref<any>({

} as any)

const formRules = reactive({
    supName: [
        { required: true, message: '请输入督办名称', trigger: 'blur' }
    ],
    userId: [
        { required: true, message: '请选择执行人', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入督办内容', trigger: 'change' }
    ],
    beginTime: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
    ],
})

/** 获取用户列表 */
const getUserList = async () => {
    try {
        userList.value = await UserApi.getSimpleUserList();
    } catch (error) {
        console.error("获取用户列表失败:", error);
        userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
    }
}
onLoad(async (options) => {
    console.log('options', options);


    detailId.value = options?.id
    resubmit.value = options?.resubmit
    await getUserList()
    /** 获得详情 */
    if (detailId.value) { await getDetailById() }

})


/** 获取页面详情 */
const getDetailById = async () => {
    try {
        const data = await SupervisionApi.getSupervision(Number(detailId.value))
        formData.value = data
        if(formData.value.url){
            fileLists.value['url'] = buildFileList(formData.value.url)
        }
    } catch (error) {
        console.log('加载数据失败')
    }
}


/** 提交表单 */
const submitForm = async (payload: any) => {
    const { type, data } = payload
    // ✅ 如果 sealId 是数组则转成字符串
    if (Array.isArray(data.sealId)) {
        data.sealId = data.sealId.join(',')
    }
    try {
        if (type === 'update') {
            await SupervisionApi.putSupervision(data)
            toast.success('编辑成功');
        } else {
            await SupervisionApi.createSupervision(data)
            toast.success('新增成功');
        }
        // 成功后跳转
        uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/supervision/index' });
    } catch (error) {
        console.error('表单提交失败:', error);
        toast.error('提交失败，请稍后再试');
    }
}

/** 取消表单 */
const cancelForm = async () => {
    try {
        // 删除的二次确认
        await message.confirm({
            msg: '您确定要取消吗？',
            title: '提示'  // 添加标题
        })
        uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/supervision/index' });
        // 显示成功提示
        toast.success('取消成功')
    } catch (error) {
        console.log('用户取消了操作或发生错误:', error)
    }
}
</script>

<style scoped lang="scss">
.container {
    padding: 20px 5px;
}

.custom-shadow {
    width: 40%;
    border-radius: 5%;
}
</style>